package com.qdlc.p2p.dal.dao.impl;

import java.util.List;

import javax.persistence.Query;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Repository;

import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.dal.common.dao.jpa.BaseDaoImpl;
import com.qdlc.p2p.dal.common.model.jpa.QueryParam;
import com.qdlc.p2p.dal.dao.UserLoginExtDao;
import com.qdlc.p2p.dal.dto.UserLoginExt;

/**
 * @author yy
 */
@Repository("userLoginExtDao")
public class UserLoginExtDaoImpl extends BaseDaoImpl<UserLoginExt> implements UserLoginExtDao {

    private static Logger logger = Logger.getLogger(UserLoginExtDaoImpl.class);

    @Override
    public long getUserIdByUserName(String userName) throws Exception {
        String sql = "SELECT userId FROM UserLoginExt WHERE userName = :userName and isDelete=0";
        Query query = em.createQuery(sql);
        query.setParameter("userName", userName);
        List rsList = query.getResultList();
        return rsList.size() == 0 ? -1 : (Long) rsList.get(0);
    }

    public int count(QueryParam param) {
        return countByCriteria(param);
    }

    @Override
    public int countByUserName(String userName) {
        return countByCriteria(QueryParam.getInstance().addParam("userName", userName));
    }

    @Override
    public void modifyUsername(long userId, String afrUsername, String preUsername) {
        String sql = "UPDATE UserLoginExt SET userName = :afrUsername WHERE userId = :userId and userName = :preUsername";
        Query query = em.createQuery(sql);
        query.setParameter("afrUsername", afrUsername);
        query.setParameter("preUsername", preUsername);
        query.setParameter("userId", userId);
        int result = query.executeUpdate();
        if (result != 1) {
            throw new UserException("更新失败！", 1);
        }
    }

    @Override
    public void deleteUsername(long userId, String userName) {
        String sql = "UPDATE UserLoginExt SET isDelete = 1 WHERE userId = :userId and userName = :username";
        Query query = em.createQuery(sql);
        query.setParameter("username", userName);
        query.setParameter("userId", userId);
        query.executeUpdate();
    }

    @Override
    public UserLoginExt getUserByUserName(String userName) {
        return super.findObjByProperty("userName", userName);
    }
    
}
